package com.its.busz.gateway.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 放行黑名单配置
 *
 * @author xiaxp
 */
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "security.unignore")
public class UnIgnoreBlackProperties {
    /**
     * 黑名单配置，网关校验
     */
    private List<String> blacks = new ArrayList<>();

    private List<Pattern> blacklistUrlPattern = new ArrayList<>();

    public boolean matchBlacklist(String url) {
        return blacklistUrlPattern.isEmpty() ?
                false : blacklistUrlPattern.stream().filter(p -> p.matcher(url).find()).findAny().isPresent();
    }

    public List<String> getBlacks() {
        return blacks;
    }

    public void setBlacklistUrl(List<String> blacks) {
        this.blacks = blacks;
        this.blacklistUrlPattern.clear();
        this.blacks.forEach(url -> {
            this.blacklistUrlPattern.add(Pattern.compile(url.replaceAll("\\*\\*", "(.*?)"),
                    Pattern.CASE_INSENSITIVE));
        });
    }
}
